"use client";
import {
    Dialog,
    DialogContent,
    DialogTrigger,
} from "@/app/ui/components/ui/dialog";
import { Label } from "../components/ui/label";
import FormField from "./form-field";
import { memo, useMemo, useState } from "react";
import { Info, TriangleAlert } from "lucide-react";
import JsonViewDialog from "./json-view-dialog";

type FormDialogProps = {
    value?: any,
    onChange?: (val: any) => void,
    children: React.ReactNode,
    columns: any[]
}

export default memo(function FormDialog({ children, value, onChange, columns }: FormDialogProps) {

    const [inputData, setInputData] = useState<any>(JSON.parse(JSON.stringify(value)));

    const onFieldValueChange = (val: any, name: string) => {
        const newInputData = {
            ...inputData,
            [name]: val
        }
        setInputData(newInputData);
        onChange && onChange(newInputData);
    }
    const renderContent = useMemo(() => {
        return columns.map((item: any) => {
            const { type, name, label, warning, placeholder, optional, rows, step = 0.1, loadMethod, options, credentialNames } = item;
            return (
                <div className='flex flex-col gap-2' key={name}>
                    {
                        warning ? <div className='flex items-center gap-2 py-3 px-2 bg-[#fefcbf] rounded-md'>
                            <TriangleAlert className="h-6 w-6 text-[orange]" />
                            <div className="text-sm">{warning}</div>
                        </div> : null
                    }
                    {
                        type !== 'json' ?
                            (
                                <FormField
                                    type={type}
                                    placeholder={placeholder}
                                    rows={rows}
                                    step={step}
                                    label={label}
                                    options={options}
                                    loadMethod={loadMethod}
                                    credentialNames={credentialNames}
                                    value={inputData[name]}
                                    onChange={(val) => onFieldValueChange(val, name)} />
                            ) :
                            (
                                <JsonViewDialog value={inputData[name]} onChange={(val) => onFieldValueChange(val, name)}></JsonViewDialog>
                            )
                    }
                </div>
            )
        })
    }, [columns]);
    return <>
        <Dialog>
            <DialogTrigger asChild>{children}</DialogTrigger>
            <DialogContent>
                {renderContent}
            </DialogContent>
        </Dialog>
    </>
});